#/bin/bash
java_file=""
alias_name=""
force_install="false"
while getopts ":f:a:F:" opt
do
    case $opt in
        f)
        java_file=$OPTARG
        echo "您输入的路径配置:$java_file"
        ;;
        a)
        alias_name=$OPTARG
        echo "您输入的快速切换指令:$alias_name"
        ;;
        F)
        force_install=$OPTARG
        echo "您输入的覆盖安装方式:$force_install"
        ;;
        ?)
        echo "未知参数,你可以这样使用 : sh installjava.sh -f ${HOME}/java.tar -a jdk8 -F true"
        exit 1;;
    esac
done
#解压至/opt/soft/java
if [ ! -d "/opt/soft/java/${alias_name}" ];then
sudo mkdir -p /opt/soft/java/${alias_name}
elif [[ "true"=="${force_install}" ]];then
  echo "您选择了覆盖模式安装"
  sudo rm -rf /opt/soft/java/${alias_name}/*
else
  echo ${alias_name}"指令已经被安装，无法重新安装...."
  exit 1
fi
if [ ! -e "${HOME}/.${USER}/profile" ]
then
  mkdir ${HOME}/.${USER}
  echo '#!bin/bash' > ${HOME}/.${USER}/profile
fi
sudo tar -zxvf ${java_file} -C /opt/soft/java/${alias_name} --strip-components=1
grep -q 'JAVA_'${alias_name}'_HOME=/opt/soft/java/'${alias_name} ~/.${USER}/profile
if [ $? -eq 1 ];then
sudo sed -i'' '$aJAVA_'"${alias_name}"'_HOME=/opt/soft/java/'"${alias_name}"'' ${HOME}/.${USER}/profile
sudo sed -i'' '$aalias '"${alias_name}"'="export JAVA_HOME=$JAVA_'"${alias_name}"'_HOME;source '"${HOME}"'/.zshrc"' ${HOME}/.${USER}/profile
fi
